package mylab.starters.cloud.common.filter;

import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import mylab.base.constants.TenantConst;
import mylab.common.context.TenantContext;
import mylab.common.context.UserContext;
import mylab.common.model.LoginUser;
import mylab.common.utils.SecurityUtil;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 租户上下文过滤器
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantContextHolderFilter extends GenericFilterBean {
    @Override
    @SneakyThrows
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        try {
            //优先取请求参数中的tenantId值
            String tenantId = request.getHeader(TenantConst.TENANT_HTTP_HEAD);
            if (StringUtil.isBlank(tenantId)) {
                String token = SecurityUtil.getHeaderToken(request);
                if (StringUtil.isNotBlank(token)) {
                    //取token中的tenantId值
                    LoginUser loginUser = SecurityUtil.getUsername(request);
                    tenantId = String.valueOf(loginUser.getTenantId());
                }
            }
            log.info("获取到的租户ID为:{}", tenantId);
            if (StringUtil.isNotBlank(tenantId)) {
                TenantContext.setTenantId(tenantId);
            } else {
                if (CharSequenceUtil.isEmpty(TenantContext.getTenantId())) {
                    TenantContext.setTenantId(TenantConst.TENANT_ID_DEFAULT);
                }
            }
            filterChain.doFilter(request, response);
        } finally {
            UserContext.clear();
        }
    }
}
